<?php

namespace App\Http\Controllers\View;

use App\Entity\CartItem;
use App\Entity\Product;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;


class CartController extends Controller
{
    public function toCart(Request $request)
    {

        $cart_items = array();
        $bk_cart = $request->cookie('bk_cart');

        $bk_cart_arr = ($bk_cart == null? array() : explode(',',$bk_cart));


        foreach ($bk_cart_arr as $key=>$value) {

            $index = strpos($value,':');
            $product_id = substr($value,0,$index);
            $count = substr($value, $index+1);

            $cartItem = new CartItem();
            $cartItem -> id = $key;
            $cartItem -> product_id = $product_id;
            $cartItem -> count = $count;

            $product = Product::query()->where('id', $product_id)->first();

            $cartItem -> product = $product;


            if ($product != null) {
                Log::info($cartItem);
                $cart_items[] = $cartItem;
            }
        }

        return view('cart')->with('cart_items',$cart_items);
    }
}
